/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * FrameDocumento.java
 *
 * Created on 16/Mai/2012, 14:43:33
 */
package smallsimulator;

import java.awt.FlowLayout;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.JPanel;
import simulador.Simulador;

/**
 *
 * @author Old
 */
public class FrameDocumento extends javax.swing.JInternalFrame {

    private ArrayList<JPanel> simFlow = new ArrayList<JPanel>();
    private boolean hasfileassoc = false;
    private File fileRel = null;
    private String fileUrl = null;
    private boolean changed = false;
    private int selId = 0;

    /** Creates new form FrameDocumento */
    public FrameDocumento() {
        initComponents();

        changed = true;

        jPanel1.setLayout(new WrapLayout(FlowLayout.CENTER, 2, 5));
        jPanel1.setSize(445, 1);

        simFlow.add((JPanel) new chegadaPanel(new chegadaInfo(0, "log", 100, 2.0f, 1.0f), this));

        simFlow.add((JPanel) new saidaPanel(this));

        updateFlow();

        this.setTitle("Novo Documento *");
        //saveToFile();
        this.setSelId(0);
    }

    public FrameDocumento(String filen) {
        initComponents();
        fileUrl = filen;
        jPanel1.setLayout(new WrapLayout(FlowLayout.CENTER, 2, 5));
        jPanel1.setSize(445, 1);
        this.setTitle(new File(fileUrl).getName());
        loadFromFile(fileUrl);
        hasfileassoc = true;
        this.setSelId(0);
    }

    public void changed() {
        if (!changed) {
            changed = true;
            this.setTitle(this.getTitle() + " *");
            System.out.println("changed doc");
        }
    }

    public void wassaved() {
        if (changed) {
            changed = false;
            this.setTitle(new File(fileUrl).getName());
        }
    }

    public int getSelId() {
        return selId;
    }

    public void setSelId(int selId) {
        ((panelItem) simFlow.get(this.selId)).setSelected(false);
        this.selId = selId;
        ((panelItem) simFlow.get(selId)).setSelected(true);
    }

    private void updateFlow() {
        jPanel1.removeAll();
        for (int i = 0; i < simFlow.size(); i++) {

            if (simFlow.get(i).getClass() == chegadaPanel.class) {
                ((chegadaPanel) simFlow.get(i)).setNum(i);
            } else if (simFlow.get(i).getClass() == saidaPanel.class) {
                ((saidaPanel) simFlow.get(i)).setNum(i);
            } else if (simFlow.get(i).getClass() == servicoPanel.class) {
                ((servicoPanel) simFlow.get(i)).setNum(i);
            } else if (simFlow.get(i).getClass() == spliterPanel.class) {
                ((spliterPanel) simFlow.get(i)).setNum(i);
            }


            jPanel1.add(simFlow.get(i));
        }
        jPanel1.revalidate();
        jPanel1.repaint();
    }

    public void saveToFile() {


        if (!hasfileassoc) {
            JFileChooser _fileChooser = new JFileChooser();
            int retval = _fileChooser.showOpenDialog(this);
            if (retval == JFileChooser.APPROVE_OPTION) {

                this.fileRel = _fileChooser.getSelectedFile();


            } else {
                return;
            }
        } else {
            this.fileRel = new File(fileUrl);
        }

        ArrayList<Object> infos = infoToArrayList();


        if (this.fileRel.exists()) {
            this.fileRel.delete();
            try {
                this.fileRel.createNewFile();
            } catch (IOException ex) {
                Logger.getLogger(FrameDocumento.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        try {
            final ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(this.fileRel));
            out.writeObject(infos);
            out.flush();
            if (!hasfileassoc) {
                fileUrl = this.fileRel.getAbsolutePath();
                hasfileassoc = true;
            }
            out.close();
            wassaved();
        } catch (IOException ex) {
            Logger.getLogger(FrameDocumento.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public ArrayList<Object> infoToArrayList() {
        ArrayList<Object> infos = new ArrayList<Object>();
        for (int j = 0; j < simFlow.size(); j++) {
            if (simFlow.get(j).getClass() == chegadaPanel.class) {
                infos.add(((chegadaPanel) simFlow.get(j)).toInfo());
            } else if (simFlow.get(j).getClass() == saidaPanel.class) {
                infos.add(((saidaPanel) simFlow.get(j)).toInfo());
            } else if (simFlow.get(j).getClass() == servicoPanel.class) {
                infos.add(((servicoPanel) simFlow.get(j)).toInfo());
            } else if (simFlow.get(j).getClass() == spliterPanel.class) {
                infos.add(((spliterPanel) simFlow.get(j)).toInfo());
            }
        }
        return infos;
    }

    public void loadFromFile(String filen) {
        try {
            final ObjectInputStream in = new ObjectInputStream(new FileInputStream(filen));
            final Object o = in.readObject();
            //System.out.println(o.getClass());
            ArrayList<Object> infos = (ArrayList<Object>) o;
            for (int j = 0; j < infos.size(); j++) {
                //System.out.println(infos.get(j).getClass());
                if (infos.get(j).getClass() == chegadaInfo.class) {
                    simFlow.add((JPanel) new chegadaPanel((chegadaInfo) infos.get(j), this));
                } else if (infos.get(j).getClass() == saidaInfo.class) {
                    simFlow.add((JPanel) new saidaPanel(this));
                } else if (infos.get(j).getClass() == servicoInfo.class) {
                    simFlow.add((JPanel) new servicoPanel((servicoInfo) infos.get(j), this));
                } else if (infos.get(j).getClass() == spliterInfo.class) {
                    simFlow.add((JPanel) new spliterPanel((spliterInfo) infos.get(j), this, infos.size()));
                }
            }
            updateFlow();
        } catch (IOException ex) {
            Logger.getLogger(FrameDocumento.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(FrameDocumento.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    public boolean validateFloat(String s) {
        boolean ret = true;
        try {
            Float.parseFloat(s);
        } catch (NumberFormatException e) {
            ret = false;
        }
        return ret;
    }

    public boolean validateInt(String s) {
        boolean ret = true;
        try {
            Integer.parseInt(s);
        } catch (NumberFormatException e) {
            ret = false;
        }
        return ret;
    }

    public void addServico() {
        if (this.selId < this.simFlow.size() - 1) {
            this.simFlow.add(this.selId + 1, (JPanel) new servicoPanel(this));
        }
        updateFlow();
        for (int i = 0; i < this.simFlow.size(); i++) {
            if (this.simFlow.get(i).getClass() == spliterPanel.class) {
                ((spliterPanel) this.simFlow.get(i)).updateMaxIndexes(this.simFlow.size(), this.selId);
            }
        }
    }

    public void addSpliter() {
        if (this.selId < this.simFlow.size() - 1) {
            this.simFlow.add(this.selId + 1, (JPanel) new spliterPanel(this));
        }
        updateFlow();
        for (int i = 0; i < this.simFlow.size(); i++) {
            if (this.simFlow.get(i).getClass() == spliterPanel.class) {
                ((spliterPanel) this.simFlow.get(i)).updateMaxIndexes(this.simFlow.size(), this.selId);
            }
        }
    }

    public void apagar() {
        if (this.selId > 0 && this.selId < this.simFlow.size() - 1) {
            this.simFlow.remove(this.selId);
            updateFlow();
            for (int i = 0; i < this.simFlow.size(); i++) {
                if (this.simFlow.get(i).getClass() == spliterPanel.class) {
                    ((spliterPanel) this.simFlow.get(i)).updateMaxIndexes(this.simFlow.size(), this.selId);
                }
            }
        }
    }

    public void correrSimulacao() {
        Simulador runner = new Simulador(this.infoToArrayList());
        runner.executa();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jPanel1 = new javax.swing.JPanel();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        setName("Form"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jPanel1.setName("jPanel1"); // NOI18N

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 466, Short.MAX_VALUE)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 483, Short.MAX_VALUE)
        );

        jScrollPane1.setViewportView(jPanel1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 485, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 315, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
